﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using wBooks.Resources;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Phone.Storage;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.Storage.Streams;
using wBooks.Entity;
using System.Text;

namespace wBooks
{
    public partial class MainPage : PhoneApplicationPage
    {
        
        public MainPage()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //List<Books> allXmlDoc = new List<Books>();
            //Books books = new Books();
            //books = XmlHelper.GetBookDetail("Bookshelf/OurLadyTears.xml");
            //allXmlDoc.Add(books);
            //this.listBoxBooks.ItemsSource = allXmlDoc;

            ListAllXMLFile("Bookshelf");
            //ListSDCardFileContents();

            //this.listBoxBooks.ItemsSource = await ListAllXMLFile(); ;
        }

        private async void ListAllXMLFile(string dataFolder)
        {
            //string[] allAuthor = await XmlHelper.GetAllAuthor(dataFolder);
            List<Books> allXmlDoc = new List<Books>();
            // settings
            // same as (ms-appx:///MyFolder/MyFile.txt)
            var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
            _Folder = await _Folder.GetFolderAsync(dataFolder);

            // acquire file
            var _File = await _Folder.GetFilesAsync();
            Books books = new Books();

            foreach (StorageFile file in _File)
            {
                if (file.Path.EndsWith(".xml"))
                {
                    books = XmlHelper.GetBookDetail(dataFolder + "/" + file.Name);
                    allXmlDoc.Add(books);
                }
            }

            this.listBoxBooks.ItemsSource = allXmlDoc;
        }

        //async Task with await
        private async Task ListSDCardFileContents()
        {

            // List the first /default SD Card whih is on the device. Since we know Windows Phone devices only support one SD card, this should get us the SD card on the phone.
            ExternalStorageDevice sdCard = (await ExternalStorage.GetExternalStorageDevicesAsync()).FirstOrDefault();
            if (sdCard != null)
            {
                // Get the root folder on the SD card.
                ExternalStorageFolder sdrootFolder = sdCard.RootFolder;
                if (sdrootFolder != null)
                {
                    // List all the files on the root folder.
                    var files = await sdrootFolder.GetFilesAsync();
                    if (files != null)
                    {
                        foreach (ExternalStorageFile file in files)
                        {
                            if (file.Path.EndsWith(".xml"))
                            {
                                //Do something later
                                //Stream s = await file.OpenForReadAsync();
                                //if (s != null || s.Length == 0)
                                //{
                                //    long streamLength = s.Length;
                                //    StreamReader sr = new StreamReader(s);
                                //    MessageBox.Show(sr.ReadToEnd());
                                //}
                                //else
                                //{
                                //    MessageBox.Show("There were no files in the root folder");
                                //}
                            }
                            else
                            {
                                MessageBox.Show("There were no xml files in the root folder");
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Failed to get root folder on SD card");
                }
            }
            else
            {
                MessageBox.Show("SD Card not found on device");
                NavigationService.Navigate(new Uri("/ReadBook.xaml?bName=OurLadyTears", UriKind.Relative));
            }
        }

        private void AB_search_Click(object sender, EventArgs e)
        {
            MessageBox.Show("search button works!");
            //Do work for your application here.
        }

        private void AB_settings_Click(object sender, EventArgs e)
        {
            MessageBox.Show("settings button works!");
            //Do work for your application here.
        }

        private void AB_delete_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Delete button works!");
            //Do work for your application here.
        }

        private void listBoxBooks_SelectionChanged(object sender,
                                         SelectionChangedEventArgs e)
        {
            if (listBoxBooks.SelectedItem != null)
            {
                Books book = (Books)listBoxBooks.SelectedItem;
                listBoxBooks.SelectedItem = null;
                Sessions.CurrentBook.Value = book.FileName;
                //this.NavigationService.Navigate(new Uri("/ReadBook.xaml?bName=" + book.FileName, UriKind.Relative));
                this.NavigationService.Navigate(new Uri("/ReadBook.xaml", UriKind.Relative));
            }
        }
    }
}